/**
 * Created by Administrator on 2017/5/10.
 */
var map = new BMap.Map("map");  // 创建Map实例
var point = new BMap.Point(119.014521, 25.459865);// 初始化地图,用城市名设置地图中心点
map.centerAndZoom(point, 15);//
map.enableScrollWheelZoom();//地图可以缩放
map.enableContinuousZoom();

var blist = [];
var districtLoading = 0;
function getBoundary() {
    addDistrict("莆田市");

}
/**
 * 添加行政区划
 * @param {} districtName 行政区划名
 * @returns  无返回值
 */
function addDistrict(districtName) {
    //使用计数器来控制加载过程
    districtLoading++;
    var bdary = new BMap.Boundary();
    bdary.get(districtName, function (rs) {       //获取行政区域
        var count = rs.boundaries.length; //行政区域的点有多少个
        if (count === 0) {
            alert('未能获取当前输入行政区域');
            return;
        }
        for (var i = 0; i < count; i++) {
            blist.push({ points: rs.boundaries[i], name: districtName });
        };
        //加载完成区域点后计数器-1
        districtLoading--;
        if (districtLoading == 0) {
            //全加载完成后画端点
            drawBoundary();
        }
    });
}

function drawBoundary() {
    //包含所有区域的点数组
    var pointArray = [];
    var pNW = { lat: 59.0, lng: 73.0 };
    var pNE = { lat: 59.0, lng: 136.0 };
    var pSE = { lat: 3.0, lng: 136.0 };
    var pSW = { lat: 3.0, lng: 73.0 };
    var pArray = [];
    pArray.push(pNW);
    pArray.push(pSW);
    pArray.push(pSE);
    pArray.push(pNE);
    pArray.push(pNW);
    //循环添加各闭合区域
    for (var i = 0; i < blist.length; i++) {
        //添加显示用标签层
        var label = new BMap.Label(blist[i].name, { offset: new BMap.Size(20, -10) });
        label.hide();
        map.addOverlay(label);

        //添加多边形层并显示
        var ply = new BMap.Polygon(blist[i].points, { strokeWeight: 1, strokeColor: "#FF0000", fillOpacity: 0.01, fillColor: " #FFFFFF" }); //建立多边形覆盖物
        ply.name = blist[i].name;
        ply.label = label;
        map.addOverlay(ply);


        //将点增加到视野范围内
        var path = ply.getPath();
        pointArray = pointArray.concat(path);
        //将闭合区域加到遮蔽层上，每次添加完后要再加一次西北角作为下次添加的起点和最后一次的终点
        pArray = pArray.concat(path);
        pArray.push(pArray[0]);
    }

    //限定显示区域，需要引用api库
    var boundply = new BMap.Polygon(pointArray);
    BMapLib.AreaRestriction.setBounds(map, boundply.getBounds());
    map.setViewport(pointArray);    //调整视野

    //添加遮蔽层
    var plyall = new BMap.Polygon(pArray, { strokeOpacity: 0.0000001, strokeColor: "#000000", strokeWeight: 0.00001, fillColor: "#000000", fillOpacity: 0.8 }); //建立多边形覆盖物
    map.addOverlay(plyall);
}
getBoundary();

//声明两个对象用来缓存marker和dangerWindow，使用id来查询和添加缓存
var cacheMap = null;
var infoWindowMap = null;

/**
 * 自定义map
 * @constructor
 */
function Map() {

    var mapObj = {};

    this.put = function (key, value) {
        mapObj[key] = value;
    };

    this.remove = function (key) {
        if (mapObj.hasOwnProperty(key)) {
            delete mapObj[key];
        }
    };

    this.get = function (key) {
        if (mapObj.hasOwnProperty(key)) {
            return mapObj[key];
        }
        return null;
    };

    this.getKeys = function () {
        var keys = [];
        for (var k in mapObj) {
            keys.push(k);
        }
        return keys;
    };

    // 遍历map
    this.each = function (fn) {
        for (var key in mapObj) {
            fn(key, mapObj[key]);
        }
    };
    this.toString = function () {
        var str = "{";
        for (var k in mapObj) {
            str += "\"" + k + "\" : \"" + mapObj[k] + "\",";
        }
        str = str.substring(0, str.length - 1);
        str += "}";
        return str;
    }

}

/**查询在百度地图上全部危险**/
function queryDanger() {
    $.ajax({
        type: "GET",
        url: "/rest/web/danger/selectDangerList",
        dataType: "json",
        data: {
            title: $("#title").val()
        },
        success: function (data) {
            cacheMap = new Map();
            infoWindowMap = new Map();

            var dangerList = data.data;
            $.each(dangerList, function (i, o) {
                setEventPoint(o);
            });
            var reportDangerHtml = "";
            var statusTotal = 0;//声明未处理的总数
            $.each(dangerList, function (i, n) {
                //查询未处理的次数
                if (n.status == "0") {
                    statusTotal = statusTotal + 1;
                }
                var status = (n.status == "0" ? "未处理" : "已完成");
                if (i == 0) {
                    getSingleDanger(n.id);
                    reportDangerHtml = reportDangerHtml + "<li data-id='" + n.id + "'> <p>" + n.createTime + "</p> <p>" + status + "</p> <p>" + n.title + "</p></li>";
                }
                else {
                    reportDangerHtml = reportDangerHtml + "<li data-id='" + n.id + "'> <p>" + n.createTime + "</p> <p>" + status + "</p><p>" + n.title + "</p></li>";
                }
            });
            $("#reportDanger").html(reportDangerHtml);
            $("#reportDanger>li").click(function () {
                getSingleDanger($(this).attr("data-id"));
            });
            //求出总数的方法
            var data = data.data;
            var dealWith = "";
            dealWith += "<div><p class='statusTotal'>未处理：<span>" + statusTotal + "</span></p><p>/总数：<span>" + data.length + "</span></p></div>";
            $(".dealWith-div").html(dealWith);
        }
    });
}
/**
 * 根据id把缓存的marker和dangerWindow拼装后调用map的openInfoWindow方法弹窗展示
 * @param id
 */
function getSingleDanger(id) {
    var infoWindow = infoWindowMap.get(id);
    var marker = cacheMap.get(id);
    querySingleDanger(id, infoWindow, marker)
}
/**
 * 绘制点危险
 * @param obj
 */

function setEventPoint(obj) {
    var dangerContent = "<div class='skuiwu-danger danger' ><div class='danger-info skuiwu-navbar navbar navbar-default navbar-static' id='myScrollspy'>" +
        "<div class='header'><h3>危险管控&nbsp;&nbsp;&nbsp;" + obj.id + "</h3></div>" +
        "<div class='content'>" +
        "<div class='message'><h2>" + obj.title + "</h2></div>" +
        "<div class='details'><h6>地址：</h6><p>" + obj.address + "</p></div>" +
        "<div class='classify'><h6>坐标：</h6><p class='coordinate'>" + obj.lng + "," + obj.lat + "</p></div>" +
        "</div></div>" +
        "</div>";
    var dangerWindow = new BMap.InfoWindow(dangerContent); // 创建信息窗口对象
    var pt = new BMap.Point(obj.lng, obj.lat);
    var myIcon = new BMap.Icon("/static/images/map_danger.png", new BMap.Size(22, 22));
    var marker = new BMap.Marker(pt, {icon: myIcon}); // 创建标注
    map.addOverlay(marker);
    marker.addEventListener("click", function () {
        querySingleDanger(obj.id, dangerWindow, marker);
    });
    //将marker和eventWindow缓存起来
    cacheMap.put(obj.id, marker);
    infoWindowMap.put(obj.id, dangerWindow);
}


/**
 * 查询单条危险信息，在原有的基础上新增详情
 * @param id  危险编号
 * @param dangerWindow  原本弹窗对象
 * @param marker  危险点
 */
function querySingleDanger(id, dangerWindow, marker) {
    $.ajax({
        type: "GET",
        url: "/rest/web/danger/selectDangerInfoList ",
        data: {
            dangerID: id
        },
        dataType: "json",
        success: function (data) {
            var dangerList = data.data;
            var reportDangerHtml = "<div data-spy='scroll' data-target='#myScrollspy' data-offset='0' class='skuiwu-scroll'>";
            $.each(dangerList, function (i, n) {
                reportDangerHtml = reportDangerHtml + "<div class='footer'>" +
                    "<div class='danger-details'>" +
                    "<div class='user-message'><img src='" + n.userIcon + "'><div><h1>" + n.nickName + "</h1><h5>" + n.department + "</h5></div></div>" +
                    "<div class='details '><h6>时间：</h6><p>" +n.createTime + "</p></div>" +
                    "<div class='details danger-content'><h6>内容：</h6><p>" + n.content + "</p></div>" +
                    "<div class='details-images'><h6>图片：</h6><ul class='images'>";
                if (n.pic != null) {
                    var imgArr = n.pic.split(",");
                    for (var j = 0; j < imgArr.length; j++) {
                        reportDangerHtml = reportDangerHtml + "<li><img src='" + imgArr[j] + "' class='imgBtn'></li>";
                    }
                }
                reportDangerHtml = reportDangerHtml + "</ul></div></div></div>";

            });
            reportDangerHtml = reportDangerHtml + "</div>";

            //获取原本的弹窗内容
            var content = dangerWindow.getContent();

            //获取data的数据拼接一个字符串
            var dangerInfo = $(content).find(".danger-info").eq(0);

            var dangerContent = "<div class='skuiwu-danger danger' >" + dangerInfo.prop('outerHTML') + reportDangerHtml + "<div>";
            /**点击照片放大效果**/
            $(".imgBtn").click(function () {
                if ($(".imgBtn").css("width") == "80px") {
                    $(this).css("width", "200px");
                } else {
                    $(this).css("width", "80px");
                }

            });
            //把原本的弹窗内容和新增的内容进行拼接
            dangerWindow.setContent(dangerContent);

            marker.openInfoWindow(dangerWindow);
            $('.images').viewer();
        }
    })
}

/**搜索框的模糊查询**/
$("#blurBtn").click(function () {
    queryDanger();
});
queryDanger();


